#pragma once

#include <string>
#include "../models/purchasemodel.hpp"
#include "../views/purchaseview.hpp"
#include "../util.hpp"
#include "../result.hpp"

namespace pharmacy_server
{
    class PurchaseController
    {
    public:
        static PurchaseController& instance()
        {
            static PurchaseController inst;
            return inst;
        }

    private:
        PurchaseController() = default;
        PurchaseController(const PurchaseController&) = delete;
        PurchaseController& operator=(const PurchaseController&) = delete;

    public:
        Result create_purchase_order(const std::string& medicine_name, const std::string& supplier, int quantity, const std::string& purchase_date)
        {
            try
            {
                purchasemodel.create_purchase_order(medicine_name, supplier, quantity, purchase_date);
                return purchaseview.create_purchase_order(true, "purchase order created successfully");
            }
            catch (const model_except& e)
            {
                return purchaseview.create_purchase_order(false, e.what());
            }
        }

        Result query_purchase_records(const std::string& medicine_name, const std::string& supplier, const std::string& purchase_date)
        {
            try
            {
                std::vector<PurchaseOrder> orders = purchasemodel.query_purchase_records(medicine_name, supplier, purchase_date);

                Json::Value root;
                for (auto& order : orders)
                    root.append(order.to_json());

                return purchaseview.query_purchase_records(true, "purchase order created successfully", json_util::serialize(root));
            }
            catch (const model_except& e)
            {
                return purchaseview.query_purchase_records(false, e.what());
            }
        }

    private:
        PurchaseModel purchasemodel;
        PurchaseView purchaseview;
    };
}